package com.rrs.client.fragment

import android.content.Context.MODE_PRIVATE
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.core.content.edit
import androidx.core.graphics.Insets
import androidx.fragment.app.Fragment
import com.google.gson.GsonBuilder
import com.rrs.client.R
import com.rrs.client.Utils
import com.rrs.client.databinding.DialogAccountBinding
import com.rrs.client.databinding.FragmentUserBinding
import com.rrs.client.entity.User
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request


class UserFragment(val systemBars: Insets?) : Fragment() {

    private lateinit var binding: FragmentUserBinding
    lateinit var utils: Utils
    val client = OkHttpClient()

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        utils = Utils(requireContext())
        //获取ViewBinding

        binding =
            FragmentUserBinding.inflate(inflater, container, false)
        // 根据系统状态栏高度设置根元素的Padding

        utils.setStatusBarPadding(binding.main)

        initLogin()
        loadData()

        binding.refresh.setColorSchemeColors(resources.getColor(R.color.colorPrimary, null))
        binding.refresh.setOnRefreshListener {
            binding.refresh.isRefreshing = false
        }

        return binding.root
    }

    open class Response {
        var result = ""
    }

    class TelCodeResponse : Response() {
        var code = ""
    }

    class ResponseWithUser : Response() {
        lateinit var user: User
    }

    @OptIn(DelicateCoroutinesApi::class)
    private fun initLogin() {
        val dialogBinding = DialogAccountBinding.inflate(layoutInflater)

        val dialog = MaterialDialog.Builder(requireContext())
            .customView(dialogBinding.root, true)
            .title("使用“乡兴助农”账号")
            .build()

        dialogBinding.codeBtn.setOnClickListener {
            val pattern = "^1[3456789]\\d{9}$".toRegex()
            val tel = dialogBinding.tel.text.toString()
            if (!pattern.containsMatchIn(tel)) {
                utils.sendMsg("请输入正确的11位手机号")
                return@setOnClickListener
            }

            GlobalScope.launch(utils.globalScopeErrorHandler) {
                var result: TelCodeResponse

                val request: Request = Request.Builder()
                    .url("${resources.getString(R.string.ServerUrl)}/getTelCode?tel=${tel}")
                    .build()

                withContext(Dispatchers.IO) {
                    client.newCall(request).execute().use { res ->
                        val resBody = res.body?.string().toString()

                        val gson = GsonBuilder()
                            .disableHtmlEscaping()
                            .setDateFormat(utils.dateFormat)
                            .create()

                        result = gson.fromJson(resBody, TelCodeResponse::class.java)
                    }
                }
                withContext(Dispatchers.Main) {
                    utils.sendMsg("[测试]验证码为${result.code}")
                }
            }
        }

        dialogBinding.submitLogin.setOnClickListener {
            val gson = GsonBuilder()
                .disableHtmlEscaping()
                .setDateFormat(utils.dateFormat)
                .create()
            val tel = dialogBinding.tel.text.toString()
            val code = dialogBinding.code.text.toString()
            if (tel.isEmpty() || code.isEmpty()) {
                utils.sendMsg("手机号或验证码还未填写")
                return@setOnClickListener
            }
            GlobalScope.launch(utils.globalScopeErrorHandler) {

                var result: ResponseWithUser

                val request: Request = Request.Builder()
                    .url("${resources.getString(R.string.ServerUrl)}/loginByTel?tel=${tel}&code=${code}")
                    .build()

                withContext(Dispatchers.IO) {
                    client.newCall(request).execute().use { res ->
                        val resBody = res.body?.string().toString()
                        result = gson.fromJson(resBody, ResponseWithUser::class.java)
                    }

                }
                withContext(Dispatchers.Main) {
                    when (result.result) {
                        "telAndCodeNotFound" -> {
                            utils.sendMsg("手机号或验证码错误")
                            return@withContext
                        }

                        "newUserRegistered" -> {
                            utils.sendMsg("注册成功")
                            val sharedPreferences =
                                requireContext().getSharedPreferences("user", MODE_PRIVATE)
                            sharedPreferences.edit {
                                putString("user", gson.toJson(result.user))
                            }
                            loadData()
                            dialog.dismiss()
                            return@withContext
                        }

                        "userLogin" -> {
                            utils.sendMsg("登录成功")
                            val sharedPreferences =
                                requireContext().getSharedPreferences("user", MODE_PRIVATE)
                            sharedPreferences.edit {
                                putString("user", gson.toJson(result.user))
                            }
                            loadData()
                            dialog.dismiss()
                            return@withContext
                        }
                    }
                }
            }
        }

        binding.login.setOnClickListener {
            dialog.show()
        }

        binding.exit.setOnClickListener {
            val sharedPreferences =
                requireContext().getSharedPreferences("user", MODE_PRIVATE)
            sharedPreferences.edit {
                putString("user", "")
            }
            utils.sendMsg("账号已退出")
            loadData()
        }
    }

    private fun loadData() {
        val sharedPreferences =
            requireContext().getSharedPreferences("user", MODE_PRIVATE)
        val gson = GsonBuilder()
            .disableHtmlEscaping()
            .setDateFormat(utils.dateFormat)
            .create()
        val userJson = sharedPreferences.getString("user", "")
        // 账号未登录
        if (userJson == "") {
            binding.username.text = "乡兴助农"
            binding.login.visibility = View.VISIBLE
            binding.exit.visibility = View.GONE
        }
        // 账号已登录
        else {
            val user = gson.fromJson(sharedPreferences.getString("user", ""), User::class.java)
            binding.username.text = user.username
            binding.login.visibility = View.GONE
            binding.exit.visibility = View.VISIBLE

        }

    }
}